package servlets.chatting;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.moma.chatting.core.ChattingManager;
import com.moma.chatting.core.Conversation;
import com.moma.chatting.core.User;

public class ConversationStart extends HttpServlet{
	private ChattingManager mgr = null;

	@Override
	public void init(){
		mgr = ChattingManager.getInstance();
		mgr.initialize();
    }
	
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		doPost(request, response);
		
	}
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		// http://messaging.com/conversationStart?id=a1,a2,a3,a4,a5&name=n1,n2,n3,n4,n5;
		String idText = request.getParameter("id");
		String nameText = request.getParameter("name");
		String[] idArray = idText.split(",");
		String[] nameArray = nameText.split(",");
		User[] userArray = new User[idArray.length];
		for (int i = 0;i < idArray.length; i++){
			String id = idArray[i];
			String name = nameArray[i];
			User user = new User();
			user.setUniqueName(id);
			user.setFriendlyName(name);
			userArray[i] = user;
		}
		Conversation conv = mgr.startConversation(userArray);
		int conversationId = conv.getConversationId();
		PrintWriter out = response.getWriter();
		
		String friendlyName = userArray[0].getFriendlyName();
		out.println(conversationId);
		out.println(friendlyName);
	}
}
